package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.BaseContext;
import com.example.common.CustomerException;
import com.example.dao.ordersDao;
import com.example.domain.*;
import com.example.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<ordersDao, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    @Transactional
    public void submit(Orders orders) {

        //获取ID
        Long userId = BaseContext.getThreadLocal();

        //查找购物车
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        if(list==null){
            throw new CustomerException("购物车为空");
        }

        User byId = userService.getById(userId);

        AddressBook byId1 = addressBookService.getById(orders.getAddressBookId());

        if(byId1==null){
            throw new CustomerException("地址不存在");
        }

        long id = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> collect = list.stream().map(shoppingCart -> {

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setName(shoppingCart.getName());


            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());


        orders.setId(id);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(id));
        orders.setUserName(byId.getName());
        orders.setConsignee(byId1.getConsignee());
        orders.setPhone(byId1.getPhone());
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setAddress((byId1.getProvinceName()==null?"":byId1.getProvinceName())
                +(byId1.getCityName()==null?"":byId1.getCityName())
                +(byId1.getDistrictName()==null?"":byId1.getDistrictName())
                +(byId1.getDetail()==null?"":byId1.getDetail())
        );



        //插入订单
        this.save(orders);


        //插入订单详情
        orderDetailService.saveBatch(collect);

        //清空购物车

        shoppingCartService.remove(wrapper);

    }

    @Override
    public void again(Long id) {

        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<OrderDetail>();

        wrapper.eq(OrderDetail::getOrderId, id);

        List<OrderDetail> list = orderDetailService.list(wrapper);



        List<ShoppingCart> shoppingCarts = list.stream().map(one->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setDishId(one.getDishId());
            shoppingCart.setNumber(one.getNumber());
            shoppingCart.setUserId(BaseContext.getThreadLocal());
            shoppingCart.setName(one.getName());
            shoppingCart.setImage(one.getImage());
            shoppingCart.setAmount(one.getAmount());
            shoppingCart.setSetmealId(one.getSetmealId());
            shoppingCart.setDishFlavor(one.getDishFlavor());
            shoppingCart.setNumber(one.getNumber());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());


        shoppingCartService.saveBatch(shoppingCarts);

    }


}
